<?php

/**
 * @var $submit Zend_Form_Element_Submit
 */
class Contest_Form_EntryField extends Contest_Form_Abstract
{
	const HELPER_CODE_FIELD		= 'fields';
	const NAME_IS_REQUIRED		= 'is_required';
	const NAME_IS_DISPLAYED		= 'is_displayed';
	const NAME_ID_ENTRY_FIELD	= 'id_entry';

    private $_isUseFullname		= true;
	private $_backupData		= null;
	public function __construct(array $options = null)
	{
		if( !empty($options) && isset($options['contest']) )
		{
			if( $options['contest'] instanceof Core_Model_Contest)
			{
				$this->_contestRow = $options['contest'];
			}
		}
		parent::__construct();
	}

	protected  function _hasBackButton() {
		return true;
	}

	protected function _initBegin()
	{
		$this->setAttrib('id', 'form_entry');
	}

	protected function _initFields()
	{
		$isNeedToLoadFromDB = false;
		if( $this->_contestRow instanceof Core_Model_Contest)
		{
			if( $this->_contestRow->isFinishedCreateEntry() )
			{
				$isNeedToLoadFromDB = true;
			}

		}
		if( $isNeedToLoadFromDB )
		{
			$this->_reloadFromDatabase();
		}
		else
		{
			$this->_intDefaultField();
		}
		$this->_backupData = $this->getValues();
	}
	/**
	 * Get id of field form db, it is used for update
	 * @todo This function is really not good, it can not use in customize field
	 *			and should be fixed for version 1.1
	 * @return Core_Model_EntryField
	 */
	private function _getEntryFieldByType($type)
	{
		$arrEntryFields		= $this->_contestRow->getListEntryFields();
		while( $arrEntryFields->current() )
		{
			$entryRow		= $arrEntryFields->current();
			if( $entryRow->type == $type)
			{
				return $entryRow;
			}
			$arrEntryFields->next();
		}
		return null;
	}

	/**
	 * @todo Should modify this function, it should gender form and use populdate to set data
	 */
	private function _reloadFromDatabase()
	{
		$arrFieldTypes	= Core_Model_DbTable_EntryFields::getListFieldTypes();
		foreach($arrFieldTypes as $type => $fieldType)
		{
			//Load form db
			$entryField = $this->_getEntryFieldByType($type);
			$type		= $type.'';
			$subForm	= new YouNet_Form_SubForm();
			//'use or not' Checkbox
			$element = new Zend_Form_Element_Checkbox($type,array(
				'label'	=> $this->getTranslator()->_($fieldType['label'])
			));
			/* @var $element Zend_Form_Element_Checkbox */
			$element->setCheckedValue(1);
			$element->setUncheckedValue(0);

			if( $type == Core_Model_IEntryFields::INDEX_FIRST_NAME )
			{
				if( !empty($entryField) && $entryField->is_displayed == Core_Model_IEntryFields::STATUS_DISPLAYED)
				{
					$this->_isUseFullname = false;
				}
			}
			//It is so hard to understanding
			//=>The correction is if is_system => it should be disabled
			if( $fieldType['is_system'] )
			{
				$element->setAttrib('readonly', 'readonly');
			}
			if( !empty($entryField) && $entryField->is_displayed == Core_Model_IEntryFields::STATUS_DISPLAYED)
			{
				$element->setChecked(true);
			}

			$subForm->addElement($element);

			//'required or optional' Radio
			/* @var $element Zend_Form_Element_Radio */
			$element = new Zend_Form_Element_Radio(self::NAME_IS_REQUIRED,array(
				'label'			=> $this->getTranslator()->_($fieldType['label']),
				'multiOptions'	=> array(
					1 => 'Required',
					0 => 'Optional',
				),
			));

			if( !empty($entryField) )
			{
				if( $entryField->is_required == 1)
				{
					$element->setValue(1);
				}
				else
				{
					$element->setValue(0);
				}
			}
			else
			{
				if( $fieldType['is_required'] == 1)
				{
					$element->setValue(1);
				}
				else
				{
					$element->setValue(0);
				}
			}
			$subForm->addElement($element);

			//Hidden
			$hiddenElement	= new Zend_Form_Element_Hidden(self::NAME_ID_ENTRY_FIELD,array());
			$value = !empty($entryField)?$entryField->id:0;
			$hiddenElement->setValue($value);
			$subForm->addElement($hiddenElement);
			
			$subForm->setElementsBelongTo(self::HELPER_CODE_FIELD.'['.$type.']');
			$subForm->setDecorators(array(array('ViewScript', array(
				'viewScript' => 'decorator/element_entry_form_custom.phtml'
			))));


			$this->addSubForm($subForm,'sub_form_field_'.$type);
		}
		$this->_addExtra();
	}

	private function _intDefaultField()
	{
		$arrFieldTypes	= Core_Model_DbTable_EntryFields::getListFieldTypes();
		foreach($arrFieldTypes as $type => $fieldType)
		{
			$type = $type.'';
			$subForm = new YouNet_Form_SubForm();

			//'use or not' Checkbox
			/* @var $element Zend_Form_Element_Checkbox */
			$element = new Zend_Form_Element_Checkbox($type,array(
				'label'			=> $this->getTranslator()->_($fieldType['label'])
			));
			$element->setCheckedValue(1);
			$element->setUncheckedValue(0);
			if( !$fieldType['is_system'] )
			{
				if( in_array($type,array(
										Core_Model_IEntryFields::INDEX_EMAIL
									)
							)
				)
				{
					$element->setChecked(true);
				}
			}
			else
			{
				if( !in_array($type,array(Core_Model_IEntryFields::INDEX_FIRST_NAME,
										Core_Model_IEntryFields::INDEX_MIDDLE_NAME,
										Core_Model_IEntryFields::INDEX_LAST_NAME))
				)
				{
					$element->setChecked(true);
				}
                $element->setAttrib('readonly', 'readonly');
			}
			$subForm->addElement($element);

			//'required or optional' Radio
			/* @var $element Zend_Form_Element_Radio */
			$element = new Zend_Form_Element_Radio(self::NAME_IS_REQUIRED,array(
				'label'			=> $this->getTranslator()->_($fieldType['label']),
				'multiOptions'	=> array(
					1 => 'Required',
					0 => 'Optional',
				),
			));

			if( $fieldType['is_required'] == 1)
			{
				$element->setValue(1);
			}
			else
			{
				$element->setValue(0);
			}
			$subForm->addElement($element);

			$subForm->setElementsBelongTo(self::HELPER_CODE_FIELD.'['.$type.']');
			$subForm->setDecorators(array(array('ViewScript', array(
				'viewScript' => 'decorator/element_entry_form_custom.phtml'
			))));

			$this->addSubForm($subForm,'sub_form_field_'.$type);
		}
		$this->_addExtra();
	}

	private function _addExtra()
	{
		$this->addElement('checkbox', 'is_using_captcha', array(
			'label'				=> 'CAPTCHA_LABEL',
			'checkedValue'		=> Core_Model_Contest::USING_CAPTCHA,
			'uncheckedValue'	=> Core_Model_Contest::NOT_USING_CAPTCHA
		));
		
		$this->is_using_captcha->setValue(Core_Model_Contest::USING_CAPTCHA);
		$this->is_using_captcha->setDescription('OPTION_SHOW_CAPTCHA');
		$this->is_using_captcha->getDecorator('Description')->setOptions(array('tag' => 'label', 'class' => '', 'for' => 'is_using_captcha'));
		$this->is_using_captcha->getDecorator('Description')->setOption('escape', false);
		
		$this->addElement('RichEditor','term_and_condition',array(
            'label'			=> $this->getTranslator()->_('TERM_AND_CONDITION'),
            'class'         => 'length_longest',
            'required'		=> true
		));
		$validatorNotEmpty = new YouNet_Validate_NotEmpty(array('type' => YouNet_Validate_NotEmpty::RICHTEXT));
		$this->term_and_condition->addValidator($validatorNotEmpty);

		$this->addElement('text','message_thanks',array(
			'label'		=> $this->getTranslator()->_('THEME_MESSAGE_THANKS'),
            'class'         => 'length_longest',
			'filters'	=> array('StringTrim')
		));
		$maxLengthValidator = new Zend_Validate_StringLength(array('max' => 255));
		$maxLengthValidator->setMessage('ERROR_MESSAGE_THANK_IS_TOO_LONG',Zend_Validate_StringLength::TOO_LONG);
		$this->message_thanks->addValidator($maxLengthValidator);
				
		foreach(array(Core_Model_IEntryFields::INDEX_FIRST_NAME,Core_Model_IEntryFields::INDEX_LAST_NAME,Core_Model_IEntryFields::INDEX_MIDDLE_NAME) as $type)
		{
			$subForm = $this->getSubForm('sub_form_field_'.$type);
			$element = $subForm->getElement($type.'');
			$element->setAttrib('class','others_name');
            $element->setAttrib('disable','disable');
			$element->setIgnore(true);
			$element->setRequired(false);
		}
		foreach(array(Core_Model_IEntryFields::INDEX_FIRST_NAME,Core_Model_IEntryFields::INDEX_LAST_NAME,Core_Model_IEntryFields::INDEX_FULL_NAME) as $type)
		{
			$subForm = $this->getSubForm('sub_form_field_'.$type);
			$element = $subForm->getElement(self::NAME_IS_REQUIRED);
            $element->setAttrib('disable','disable');
			$element->setIgnore(true);
			$element->setRequired(false);
		}

		$subFormFullename	= $this->getSubForm('sub_form_field_'.Core_Model_IEntryFields::INDEX_FULL_NAME);
		$fullname			= $subFormFullename->getElement(Core_Model_IEntryFields::INDEX_FULL_NAME.'');
		$fullname->setAttrib('id','fullname');
		$fullname->setAttrib('readonly',null);
        if( !$this->_isUseFullname )
		{
			$fullname->setChecked(false);
		}
	}
	/**
	 *
	 * @param Core_Model_Contest $contestRow
	 * @return Contest_Form_EntryField
	 */
	public function fill(Core_Model_Contest $contestRow)
	{
		$data		= $contestRow->toArray();
		$this->populate($data);
		return $this;
	}

	public function disableFields()
	{

	}

	public function render(Zend_View_Interface $view = null)
	{
		if( isset($_POST['form_submitted']) )
		{
			if( !($this->_contestRow instanceof Core_Model_Contest) )
			{
				throw new Exception('Need to set _contestRow to populate disable value');
			}

			if( isset($this->_backupData['term_and_condition']) )
			{
				unset($this->_backupData['term_and_condition']);
			}
			if( isset($this->_backupData['message_thanks']) )
			{
				unset($this->_backupData['message_thanks']);
			}

            if( empty($_POST[self::HELPER_CODE_FIELD][Core_Model_IEntryFields::INDEX_FULL_NAME][Core_Model_IEntryFields::INDEX_FULL_NAME]) )
            {
                unset($this->_backupData[self::HELPER_CODE_FIELD][Core_Model_IEntryFields::INDEX_FULL_NAME][Core_Model_IEntryFields::INDEX_FULL_NAME]);
                $_POST[self::HELPER_CODE_FIELD][Core_Model_IEntryFields::INDEX_MIDDLE_NAME][Core_Model_IEntryFields::INDEX_MIDDLE_NAME] = 1;
                $_POST[self::HELPER_CODE_FIELD][Core_Model_IEntryFields::INDEX_FIRST_NAME][Core_Model_IEntryFields::INDEX_FIRST_NAME] = 1;
                $_POST[self::HELPER_CODE_FIELD][Core_Model_IEntryFields::INDEX_LAST_NAME][Core_Model_IEntryFields::INDEX_LAST_NAME] = 1;
            }
            $_POST[self::HELPER_CODE_FIELD][Core_Model_IEntryFields::INDEX_FULL_NAME][self::NAME_IS_REQUIRED] = 1;
            $_POST[self::HELPER_CODE_FIELD][Core_Model_IEntryFields::INDEX_FIRST_NAME][self::NAME_IS_REQUIRED] = 1;
            $_POST[self::HELPER_CODE_FIELD][Core_Model_IEntryFields::INDEX_LAST_NAME][self::NAME_IS_REQUIRED] = 1;
            $this->populate(array_merge(
                $this->_backupData,
                $_POST
            ));
		}
		/*
		 * remove button cancel and back
	     */
        $this->removeButton();
		return parent::render($view);
	}
};